//
//  SEGOrderPayListViewController.m
//  SEGUhomePropertyBaseService
//
//  Created by Clavis on 2018/10/18.
//  Copyright © 2018 刘山. All rights reserved.
//

// VC
#import "SEGOrderPayListViewController.h"
#import "SEGOrderDetailController.h"
#import "SEGOrderInputViewController.h"
#import "SEGSignViewController.h"
// View
#import "SEGOrderPayListCell.h"
#import "SEGSignSuccessView.h"
// Model
#import "SEGOrderDetailManager.h"

#if __has_include(<WXApi.h>)
#import <WXApi.h>
#else
#import "WXApi.h"
#endif

#define kCellIdentifier @"kCellIdentifier"
#define kMaxRequestCount 10

@interface SEGOrderPayListViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *payButton;
@property (nonatomic, assign) NSInteger currentSelectIndex;
//@property (nonatomic, retain) PayListRequestModel* payListRequestModel;
@property (nonatomic, assign) NSInteger requestCount;

@end

@implementation SEGOrderPayListViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"🛫🛫🛫🛫 %s", __func__);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupData];
    [self.tableView reloadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:@"ORDER_PAY_NOTIFICATION" object:nil];
}

- (void)setupUI {
    self.title = @"待支付";
    [self showCustomNavigationBackButton];
    
    self.view.backgroundColor = kColor_bg;
    UIView *payAmountView = ({
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = kColor_W;
        UILabel *titleLable = ({
            UILabel *lable = [[UILabel alloc] init];
            lable.font = kFont_16;
            lable.textColor = kColor_1;
            lable.text = @"支付金额";
            [view addSubview:lable];
            lable;
        });
        [titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(view);
            make.top.mas_equalTo(30);
        }];
        UILabel *amountLabel = ({
            UILabel *lable = [[UILabel alloc] init];
            lable.textColor = kColor_1;
            [view addSubview:lable];
            NSMutableAttributedString *amountString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f",self.amount] attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:36]}];
            [amountString appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" 元" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:24]}]];
            lable.attributedText = amountString;
            lable;
        });
        [amountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(titleLable);
            make.top.equalTo(titleLable.mas_bottom).offset(25);
        }];
        
        UIView *grayView = [[UIView alloc] init];
        grayView.backgroundColor = kColor_bg;
        [view addSubview:grayView];
        UILabel *tipLabel = ({
            UILabel *lable = [[UILabel alloc] init];
            lable.font = kFont_13;
            lable.textColor = kColor_3;
            lable.text = @"账单已经生成，请选择支付方式";
            [grayView addSubview:lable];
            lable;
        });
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(13);
            make.top.mas_equalTo(15);
            make.bottom.mas_equalTo(-10);
        }];
        [grayView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(view);
            make.top.equalTo(amountLabel.mas_bottom).offset(40);
        }];
        view;
    });
    [self.view addSubview:payAmountView];
    [payAmountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.mas_equalTo(0);
    }];
    
    self.payButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *typeName = @"";
        if (self.dataSource.count >= 1) {
            typeName = self.dataSource.firstObject.name;
        }
        NSString *title = [@"使用" stringByAppendingString:typeName];
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:kColor_W forState:UIControlStateNormal];
        button.backgroundColor = kColor_T;
        [button setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(payButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, LYSafeAreaBottom(), 0);
        [self.view addSubview:button];
        button;
    });
    [self.payButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(44 + LYSafeAreaBottom());
    }];
    
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = kColor_bg;
        tableView.rowHeight = 44;
        [tableView registerClass:[SEGOrderPayListCell class] forCellReuseIdentifier:kCellIdentifier];
        tableView.separatorColor = kColor_L2;
        tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, -15);
        tableView.bounces = NO;
        tableView.tableFooterView = [[UIView alloc] init];
        [self.view addSubview:tableView];
        tableView;
    });
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(payAmountView.mas_bottom);
        make.bottom.equalTo(self.payButton.mas_top);
    }];
}

- (void)setupData {
//    self.payListRequestModel = [[PayListRequestModel alloc] init];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGOrderPayListCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];
    SEGWorkOrderPayListModel *payModel = self.dataSource[indexPath.row];
    [cell updateCellWithModel:payModel isSelect:indexPath.row == self.currentSelectIndex];
    __weak typeof(self) weakSelf = self;
    cell.selectBlock = ^{
        weakSelf.currentSelectIndex = indexPath.row;
        [weakSelf.payButton setTitle:[@"使用" stringByAppendingString:payModel.name] forState:UIControlStateNormal];
        [weakSelf.tableView reloadData];
    };
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

#pragma mark - Action
- (void)payButtonTap:(UIButton *)sender {
    SEGWorkOrderPayListModel *model = self.dataSource[self.currentSelectIndex];
    if ([model.code isEqualToString:@"MERGE"]) {
        // 使用合并账单支付
        SEGSignViewController *signVC = [[SEGSignViewController alloc] init];
        signVC.completeBlock = ^(UIImage *image) {
            __weak typeof(self) weakSelf = self;
            [SVProgressHUD show];
            
            [[SEGOnefileuploadManager sharedManager] requestOnefileuploadWithImage:image progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
                if (isSuccessed) {
                    [weakSelf submitCombineBillPayWithSignURL:result[@"data"]];
                } else {
                    [SVProgressHUD dismiss];
                    [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
                }
            }];
        };
        [self.navigationController pushViewController:signVC animated:YES];
    } else if ([model.code isEqualToString:@"WXORI_APP_WEIXIN"]) {
        // 使用微信支付
        [self submitWeiChatPay];
    }else if ([model.code containsString:@"UMSPAY_QMF"]) {
        // 使用银联支付
        [self initUMSPAY];
    } else {
        [SEGAlertView showTmepMessageWithMessage:@"请升级到最新的版本完成支付"];
    }
}

- (void)initUMSPAY {
    [SVProgressHUD show];
    
    SEGWorkOrderPayListModel *model = self.dataSource[self.currentSelectIndex];
    NSDictionary *param = @{@"organId"        :self.organId,
                            @"serviceOrderId" :self.serviceOrderId,
                            @"payMethod"      :model.payMethod ?: @"",
                            @"payChannel"     :@"1",
                            @"tradeType"      :model.code ?: @"",
                            @"appId": [SEGBasicBussinessCommonDefine segWeChatAppId] ?: @""
                            };
    [[SEGOrderDetailManager sharedManager] onlinePay:param finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (isSuccessed && result[@"data"][@"resultCode"] != nil && [result[@"data"][@"resultCode"] integerValue] == 0) {
            if (result[@"data"][@"payInfo"]) {
                NSDictionary *payInfo = [self dictionaryWithJsonString:result[@"data"][@"payInfo"]];
                NSDictionary *param = @{
                        @"dict": payInfo,
                        @"payCode": model.alaisName,
                        @"payChannel": model.code
                };
                [[SEGUhomeMediator sharedInstance] seg_initPayAction:param];
            }
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}

#pragma mark - handle
// 合并账单支付
- (void)submitCombineBillPayWithSignURL:(NSString *)signURL {
    NSDictionary *param = @{@"organId":self.organId,
                            @"serviceOrderId":self.serviceOrderId,
                            @"payMethod":@"2",
                            @"trackId":self.trackId,
                            @"sign":signURL
                            };
    
    
    WeakSelf;
    [[SEGOrderDetailManager sharedManager] combineBillPay:param finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (isSuccessed) {
            [weakSelf handlePaySuccess:NO];
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}

- (void)handlePaySuccess:(BOOL)isWeixinPay {
    __weak typeof(self) weakSelf = self;
    SEGSignSuccessView *successView = [[SEGSignSuccessView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    if (isWeixinPay) {
        successView.tipLabel.text = @"支付成功";
    }
    successView.backHomeBlock = ^{
        // 对当前导航栈做处理
//                NSMutableArray *tempArray = [[NSMutableArray alloc] init];
//                for (UIViewController *vc in weakSelf.navigationController.viewControllers) {
//                    [tempArray addObject:vc];
//                    if ([vc isKindOfClass:[SEGOrderInputViewController class]]) {
//                        break;
//                    }
//                }
//                weakSelf.navigationController.viewControllers = tempArray;
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    };
    successView.backOrderDetailBlock = ^{
        // 对当前导航栈做处理
        NSMutableArray *tempArray = [[NSMutableArray alloc] init];
        for (UIViewController *vc in weakSelf.navigationController.viewControllers) {
            [tempArray addObject:vc];
            if ([vc isKindOfClass:[SEGOrderDetailController class]]) {
                // 设置需要更新数据
                ((SEGOrderDetailController *)vc).needReloadData = YES;
                break;
            }
        }
        weakSelf.navigationController.viewControllers = tempArray;
    };
    [[UIApplication sharedApplication].keyWindow addSubview:successView];
}

- (void)submitWeiChatPay {
    [SVProgressHUD show];
    
    SEGWorkOrderPayListModel *model = self.dataSource[self.currentSelectIndex];
    NSDictionary *param = @{@"organId"        :self.organId,
                            @"serviceOrderId" :self.serviceOrderId,
                            @"payMethod"      :model.payMethod ?: @"",
                            @"payChannel"     :@"1",
                            @"tradeType"      :model.code ?: @"",
                            @"appId": [SEGBasicBussinessCommonDefine segWeChatAppId] ?: @""
                            };
    WeakSelf;
    [[SEGOrderDetailManager sharedManager] onlinePay:param finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        [SVProgressHUD dismiss];
        if (isSuccessed && result[@"data"][@"resultCode"] != nil && [result[@"data"][@"resultCode"] integerValue] == 0) {
            // 只有在 resultCode == 0 的时候请求成功
            [weakSelf weixinPayWithParams:result[@"data"]];
        } else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}

- (void)weixinPayWithParams:(NSDictionary*)dic {
    NSDictionary *payinfo = [dic[@"payInfo"] jsonValueDecoded];
    NSDictionary *params = @{@"dataDic":@{@"payInfo":payinfo,@"payCode":@"WEIXIN"}};
    
    [[SEGUhomeMediator sharedInstance] seg_sendPayForPayOnLineWithParams:params];
}

#pragma mark - handle notification
- (void)getOrderPayResult:(NSNotification *)notification{
    if ([notification.object isEqualToString:@"success"]) {
        //支付成功页面
        [self handlePaySuccess:YES];
    } else if ([notification.object isEqualToString:@"WXErrCodeUserCancel"]) {
        [SEGAlertView showTmepMessageWithMessage:@"支付已取消"];
    } else {
        
    }
    

    /*
     轮询查询支付状态，暂时不处理
     NSString *url = [SEGServerManager serverUrlJoint:kClientRootURL,@"/order-user-api/rest-api/v5/order/paid/checkOrderPayFlag.json",nil];
     NSDictionary *param = @{@"organId"          : self.organId,
                             @"serviceOrderId"   : self.serviceOrderId
     };
     [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:url parameters:param finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
         NSLog(@"result = %@", result);
     }];
     */
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


@end
